/**
	@file
	Kernel functions error system. Provides functions for setting and getting functions error result.
	Almost all kernel functions sets lastError variable (see documentation of each function for further
	information). All error codes are defines in \ref errno.h 
	(already included in errors.h). Call \ref getLastError() to get the last occured error code.
	If function (whatever which one) returned successfully, then lastError will be set to zero
	(\ref NO_ERROR).
	
	@author Konstantin Kastanov
*/
#include "headers/errors.h"
#include "headers/errno.h"
#include "headers/errorMessages.h"
#include "headers/dataTypes.h"

static u8int lastError = NO_ERROR;

/**
	@return Last occurred error code.
	@see errno.h
*/
u8int getLastError()
{
	return lastError;
}

/**
	Sets last error. If errorCode is not valid, \ref ERR_UNKNOWN is set.
	@param errorCode New error code
	@return Previous Last error value
*/
u8int setLastError(u8int errorCode)
{
	u8int saveLast;

	saveLast = lastError;
	if(errorCode > (NUMBER_OF_ERROR_CODES - 1))  //zero based.  If errorCode = ERR_UNKNOWN, still the correct value will be assigned, ass ERR_UNKNOWN >= NUMBER_OF_ERROR_CODES
		lastError = ERR_UNKNOWN;
	else
		lastError = errorCode;

	return saveLast;
}

/**
	Converts error code to it's text description
	@param errorCode Error code to convert
	@return Pointer to a char array, representing the error code.
*/
s8int* getErrorMessage(u8int errorCode) 
{
	if((errorCode == ERR_UNKNOWN) || (errorCode > (NUMBER_OF_ERROR_CODES - 1)))
		return ERR_UNKNOWN_MESSAGE;
	else
		return messages[errorCode];
}

/**
	Equivalent to getErrorMessage(getLastError())
	@return Last occurred error in text form
*/
s8int* getLastErrorMessage()
{
	return getErrorMessage(lastError);
}

